package org.jakim.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.jakim.db.HibernateUtil;
import org.jakim.entity.User;

/**
 * Servlet implementation class RegistrationServlet
 */
public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegistrationServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userEmail = request.getParameter("userEmail");
		String userPassword = request.getParameter("userPassword");
		HttpSession httpSeesion = request.getSession();

		Session hibernateSession = HibernateUtil.getSessionFactory()
				.openSession();
		hibernateSession.beginTransaction();

		Criteria userCriteria = hibernateSession.createCriteria(User.class);

		User user = (User) userCriteria.add(
				Restrictions.eq("userEmail", userEmail)).uniqueResult();

		if (user == null) {

			User newUser = new User();
			newUser.setUserEmail(userEmail);
			newUser.setUserPassword(userPassword);

			hibernateSession.save(newUser);
			hibernateSession.getTransaction().commit();
			hibernateSession.close();

			httpSeesion.setAttribute("User", newUser);
			response.sendRedirect("registrationcomplete.jsp");

		} else {
			hibernateSession.close();
			httpSeesion.setAttribute("isUserExist", true);
			response.sendRedirect("registration.jsp");
		}
	}

}
